<template>
  <div class="page-box">
    <TableFilter
      :data="filter"
      v-model="query"
      ref="filter"
      @change="changeFilter"
    >
      <template v-slot:topBtns>
        <el-upload
          style="margin-left: 10px"
          class="upload-demo"
          action=""
          :before-upload="changeFile"
          :show-file-list="false"
        >
          <el-button slot="trigger" size="small" type="primary">导入</el-button>
        </el-upload>
      </template>
    </TableFilter>

    <el-table
      ref="singleTable"
      highlight-current-row
      @current-change="changeRow"
      :header-cell-style="{ background: '#f2f2f2', lineHeight: '50px' }"
      border
      :data="tableData1"
      style="width: 100%"
    >
      <el-table-column prop="lb" label="类别"> </el-table-column>
      <el-table-column prop="bm" label="编码"> </el-table-column>
      <el-table-column prop="fb" label="费别"> </el-table-column>
      <el-table-column prop="mc" label="收费项目名称" width="200">
      </el-table-column>
      <el-table-column prop="sj" label="售价"> </el-table-column>
      <el-table-column prop="sjdw" label="单位"> </el-table-column>
      <el-table-column prop="fy1" label="人力资源成本" width="120">
      </el-table-column>
      <el-table-column prop="fy2" label="药品成本"> </el-table-column>
      <el-table-column prop="fy3" label="计费耗材成本" width="120">
      </el-table-column>
      <el-table-column prop="fy4" label="不计费耗材成本" width="130">
      </el-table-column>
      <el-table-column prop="fy5" label="固定资产折旧成本" width="140">
      </el-table-column>
      <el-table-column prop="fy6" label="其他成本"> </el-table-column>

      <!-- <el-table-column prop="ybbm" label="医保编码" width="260"> -->
      <el-table-column prop="操作" label="操作" width="140">
        <template slot-scope="{ row }">
          <el-button type="text" @click="openAdd(row)">设置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.page"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="query.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <el-dialog
      :close-on-click-modal="false"
      title="成本项目设置"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        :model="formData"
        ref="formRef"
        :rules="rules"
        label-width="130px"
      >
        <el-form-item label="收费项目成本" prop="sfxmbm">
          <el-select
            filterable
            remote
            :remote-method="remoteMethod"
            :loading="loading"
            v-model="formData.sfxmbm"
            placeholder="请选择"
            clearable
            style="width: 100%"
            @change="changeItem"
          >
            <el-option
              v-for="(v, i) in selectOption"
              :key="i"
              :label="v.mc"
              :value="v.bm"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人力资源成本" prop="fy1">
          <el-input
            type="number"
            v-model="formData.fy1"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="药品成本" prop="fy2">
          <el-input
            type="number"
            v-model="formData.fy2"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="计费耗材成本" prop="fy3">
          <el-input
            type="number"
            v-model="formData.fy3"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="不计费耗材成本" prop="fy4">
          <el-input
            type="number"
            v-model="formData.fy4"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="固定资产折旧成本" prop="fy5">
          <el-input
            type="number"
            v-model="formData.fy5"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="其他成本" prop="fy6">
          <el-input
            type="number"
            v-model="formData.fy6"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
name: "constService";
import TableFilter from "@/components/TableFilter";
import { getCostList, saveCostRef, delCostRef } from "@/api/constService";
import { UserModule } from "@/store/modules/user";
import { read, utils } from "xlsx";
export default {
  components: {
    TableFilter,
  },
  data() {
    return {
      UserModule: UserModule,
      loading: false,
      formData: {
        sfxmbm: "",
        fy1: "",
        fy2: "",
        fy3: "",
        fy4: "",
        fy5: "",
        fy6: "",
      },
      selectOption: [],
      rules: {
        sfxmbm: [{ required: true, message: "请选择", trigger: "change" }],
        // price: [{ required: true, message: "请输入", trigger: "blur" }],
        num: [{ required: true, message: "请输入", trigger: "blur" }],
        resultNum: [{ required: true, message: "请输入", trigger: "blur" }],
        jsfs: [{ required: true, message: "请选择", trigger: "change" }],
      },
      dialogVisible: false,
      total: 0,
      totalPrice: "",
      query: {
        fylb: "",
        lb: 1,
        page: 1,
        size: 10,
        zt: 1,
        keys: "",
      },
      tableData1: [],
      tableData2: [],
      currentRow: null,
      addForm: {},
      fbList: [],
      rowData: {},
      importTable: [],
    };
  },
  computed: {
    filter() {
      return {
        inline: [
          {
            props: {
              label: "费别",
              is: "el-select",
              filterable: true,
              options: [{ label: "全部", value: "" }].concat(this.fbList),
            },

            keys: "fylb",
          },
          {
            props: {
              label: "状态",
              is: "el-select",
              options: [
                { label: "启用", value: 1 },
                { label: "停用", value: 0 },
              ],
            },
            keys: "zt",
          },
          {
            props: {
              label: "关键字",
              is: "el-input",
            },
            data: {
              attrs: {
                placeholder: "请输入",
              },
            },
            keys: "keys",
          },
        ],
      };
    },
  },
  created() {
    this.getTableData();
    this.getFbList();
  },
  methods: {
    changeFile(file) {
      let ExcalBar = ["xlsx", "xlsm", "xltx", "xls"];
      const isExcal =
        ExcalBar.indexOf(file.name.substring(file.name.lastIndexOf(".") + 1)) >
        -1
          ? true
          : false;
      if (!isExcal) return this.$message.warning("文件格式不正确");
      if (file) {
        this.readExcelFile(file)
          .then((data) => {
            console.log(data);
            // 在这里处理读取到的Excel数据
            this.importTable = data.slice(1).reduce((pre, cur) => {
              let obj = {};
              cur.forEach((v, i) => {
                obj[data[0][i]] = v;
              });
              pre = [...pre, obj];
              return pre;
            }, []);
            console.log(this.importTable, "xxx");
            this.importAllDatas(this.importTable);
          })
          .catch((error) => {
            console.error(error);
          });
      }
      return false;
    },
    readExcelFile(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = new Uint8Array(e.target.result);
          const workbook = read(data, { type: "array" });
          const worksheet = workbook.Sheets[workbook.SheetNames[0]];
          const jsonData = utils.sheet_to_json(worksheet, { header: 1 });
          resolve(jsonData);
        };
        reader.onerror = (e) => {
          reject(e);
        };
        reader.readAsArrayBuffer(file);
      });
    },
    async importAllDatas(list) {
      const allImport = list.map((v) => {
        const {
          HIS项目编码,
          不计费耗材成本,
          人力资源成本,
          其他成本,
          名称,
          固定资产折旧成本,
          收费项目ID,
          类别,
          药品成本,
          规格,
          计费耗材成本,
        } = v;
        const params = {
          czry: this.UserModule.user,
          fy1: 人力资源成本,
          fy2: 药品成本,
          fy3: 计费耗材成本,
          fy4: 不计费耗材成本,
          fy5: 固定资产折旧成本,
          fy6: 其他成本,
          sfxmbm: HIS项目编码,
          sfxmid: 收费项目ID,
        };
        return saveCostRef(params);
      });
      await Promise.all(allImport);
      this.$message.success("操作成功");
    },
    handleClose() {
      this.dialogVisible = false;
    },
    openAdd(row) {
      this.$set(this, "selectOption", [row]);
      setTimeout(() => {
        this.dialogVisible = true;
        this.rowData = row;
        const { fy1, fy2, fy3, fy4, fy5, fy6, sfxmid } = row;
        this.formData = {
          ...this.formData,
          fy1,
          fy2,
          fy3,
          fy4,
          fy5,
          fy6,
          sfxmid,
          sfxmbm: row.bm,
        };
      }, 0);
      // this.remoteMethod("");
    },
    changeFilter(e) {
      let data = {
        ...e,
      };
      for (let key in data) {
        if (!data[key] && data[key] != 0) delete data[key];
      }
      this.query = data;

      this.getTableData();
    },
    async getTableData() {
      console.log("获取数据----");
      const res = await getCostList(this.query);
      this.tableData1 = res.data.records;
      this.$nextTick(() => {
        this.setCurrent(this.tableData1[0]);
      });
      this.total = res.data.total;
    },
    //获取筛选条件费别列表
    async getFbList() {
      const params = {
        ...this.query,
        lb: 2,
        keys: "",
        // xmbm: this.currentRow?.his项目编码,
      };
      const res = await getCostList(params);
      this.fbList = res.data.map((v) => ({ label: v.fb, value: v.fb }));
    },
    async getTwoTableData() {
      return; //取消列表2的调用
      const params = {
        ...this.query,
        lb: 2,
        xmbm: this.currentRow?.his项目编码,
      };
      const res = await getCostList(params);
      this.tableData2 = res.data;
      this.totalPrice = res.data.reduce((pre, cur) => {
        pre += cur.cbj;
        return pre;
      }, 0);
    },
    handleSizeChange(val) {
      this.query.size = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.query.page = val;
      this.getTableData();
    },
    changeRow(val) {
      this.currentRow = val;
      if (!val) return;
      this.getTwoTableData();
    },
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row);
    },
    async remoteMethod(e) {
      const params = {
        ...this.query,
        keys: e,
        xmbm: this.currentRow?.his项目编码,
      };
      this.loading = true;
      const res = await getCostList(params);
      this.selectOption = res.data.records;
      this.loading = false;
    },
    changeItem(e) {
      console.log(e);
      // const item = this.selectOption.find((v) => v.his项目编码 === e);
      // this.formData.price = item.售价;
    },
    initFormData() {
      this.formData = {
        sfxmbm: "",
        fy1: "",
        fy2: "",
        fy3: "",
        fy4: "",
        fy5: "",
        fy6: "",
      };
    },
    submit() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;
        console.log("提交", this.UserModule);
        const params = {
          ...this.formData,
          cbid: this.currentRow.cbid,
          // cbxmbm: this.currentRow?.his项目编码,
          // sfxmmc: this.selectOption.find(
          //   v => v.bm === this.formData.sfxmbm
          // )?.mc,
          czry: this.UserModule.user,
        };
        await saveCostRef(params);
        this.$message.success("操作成功");
        this.dialogVisible = false;
        this.getTableData();
        this.initFormData();
        // this.getTwoTableData();
      });
    },
    async delItem(row) {
      const confirm = await this.$confirm("是否确认删除？", "提示", {
        type: "warning",
      });
      if (confirm !== "confirm") return;
      await delCostRef({ id: row.id });
      this.$message.success("操作成功");
      this.getTwoTableData();
    },
  },
};
</script>

<style lang="scss" scoped>
.page-box {
  padding: 20px;
}
::v-deep .el-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: end;
}
.btns-add {
  display: flex;
  justify-content: end;
}
::v-deep .el-table .el-table__cell {
  padding: 2px 0;
}
::v-deep .el-form-item__content {
  display: flex;
}
::v-deep .el-input__inner {
  width: 100%;
}
</style>
